var fs = require('fs');
var express = require('express');
var multer  = require('multer');
const { exec } = require('child_process');
const path = require('path');
var os = process.platform;
var command = '';
if (os === 'linux')
	command = './Y86.out upload/upload.yo';
else
	command = '.\\Y86.exe upload\\upload.yo';


var app = express();
app.use(express.static('public'));

var createFolder = function(folder){
    try{
        fs.accessSync(folder); 
    }catch(e){
        fs.mkdirSync(folder);
    }  
};

var uploadFolder = './upload/';

createFolder(uploadFolder);

// 通过 filename 属性定制
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder);    // 保存的路径，备注：需要自己创建
    },
    filename: function (req, file, cb) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        cb(null, "upload.yo");  
    }
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })

app.post('/upload', upload.single('file'), function(req, res, next){
    var file = req.file;
    var ret;
    // './Y86.out upload/upload.yo'
    exec(command, (err, stdout, stderr) => {  
        if(err) {
            console.log(err);
            return;
        }
    console.log(`exec succeeded`);
        ret = stdout;
        res.send(ret.replace(/\r\n/g, "\n"));
    });
    // res.send(ret);
});

app.get('/', function(req, res, next){
    var form = fs.readFileSync('./Y86.html', {encoding: 'utf8'});
    res.send(form);
});

app.listen(8080);
